#include "LabelHashTable.h"
//necessary
#include "memory-tools.h"
#include <stdlib.h>

void initLabelHashTable(PlabelHashTable phashtable){
	*phashtable=NULL;
}

Plabel findLabelInHashTable(PlabelHashTable phashtable,const char* key){
	PlabelHTCell result;
	HASH_FIND_STR(*phashtable,key,result);
	if (result==NULL){
		return NULL;
	}
	return result->label;
}

void addLabelInHashTable(PlabelHashTable phashtable, Plabel label){
	PlabelHTCell cell=initLabelHTCell(label);
	HASH_ADD_KEYPTR(hh,*phashtable,cell->key,strlen(cell->key),cell);
}


void freeLabelHashTable(PlabelHashTable phashtable){
	PlabelHTCell element;
	PlabelHTCell tmp;

	HASH_ITER(hh,*phashtable,element,tmp){
		HASH_DEL(*phashtable,element);
		freeLabelHTCell(element);
	}
}

bool buildLabelHashTableGraph(char* filename,PlabelHashTable phashtable){
	char dotname[__LABEL_HASH_TABLE_BUFFER_SIZE__];
	char command[2*__LABEL_HASH_TABLE_BUFFER_SIZE__+25];
	int items;

	sprintf(dotname,"grp/%s.dot",filename);
	FILE* f=fopen(dotname,"w");
	if (f==NULL){
		fprintf(stderr,"can't create the file \"%s\"!\n",dotname);
		return false;
	}
	fprintf(f,"digraph labelhashtable {\n");
	fprintf(f,"\trankdir=LR;\n");
	//generation of the node representing the hash table. This representation is not the real representation of the

	items=HASH_COUNT(*phashtable);
	fprintf(f,"\ttable [shape=\"record\" label=\"");
	int i;
	for (i=0;i<items;i++){
		fprintf(f,"<f%03d>|",i);
	}
	fprintf(f,"\"];\n");
	//generation of the nodes attached to the hash table

	LabelHashTable tmp;
	for (tmp=*phashtable, i=0; tmp!=NULL; tmp=tmp->hh.next, i++){
		fprintf(f,"\t");
		generateDOTLabelHTCell(f,tmp,i);
		fprintf(f,"\n");
		fprintf(f,"\ttable:f%03d -> n%03d;\n",i,i);
	}
	fprintf(f,"\n");
	fprintf(f,"}\n");
	fflush(f);
	fclose(f);

	//generates the JPG image
	sprintf(command,"dot -Tjpg grp/%s.dot -o grp/%s.jpg",filename,filename);
	int result=system(command);
	if (result!=0){
		fprintf(stderr,"LabelHashTable.c:buildLabelHashTableGraph:can't compile the file \"grp/%s.dot\"!\n",filename);
		return false;
	}
	sprintf(command,"rm %s",dotname);
	result=system(command);
	if (result!=0){
		fprintf(stderr,"can't remove \"%s\" file!\n",dotname);
		return false;
	}
	return true;
}
